package com.woniu.config;

import com.woniu.pojo.User;
import com.woniu.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService UserService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权_doGetAuthorizationInfo");

        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addStringPermission("user:add");
        //拿到当前登录对象
        Subject subject= SecurityUtils.getSubject();
        User currentUser= (User) subject.getPrincipal();//拿到user对象
        //设置当前用户权限
//        info.addStringPermission(currentUser.getParms());

        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=>认证_doGetAuthenticationInfo");
        UsernamePasswordToken userToken= (UsernamePasswordToken) token;
        //连接数据库（根据账户号查询）
        User user = UserService.findOneByUaccount(userToken.getUsername());

        if(user==null){//没有这个人
            return  null;//UnKnownAccountException
        }
        return new SimpleAuthenticationInfo(user,user.getUpwd(),"");
    }
}
